package com.bblocks.util;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * @description:百度地图工具类,可能未初始（未配置参数：bblocks.map.baiduAk）
 * @author: xingdong
 * @time: 2020/6/4 下午3:01
 */
@Component
@ConditionalOnProperty(name = "bblocks.map.baiduAk", matchIfMissing = true)
@Slf4j
public class MapUtil {

    public static final Charset DEFAULT_CHARSET =  Charset.forName("utf-8");

    public static final String _baseUrl = "http://api.map.baidu.com/directionlite/v1/driving?";

    /**
     * 公司百度账户,测试用个人账户：xncraBwKF8YGi1GoYKpFYxq4tvNw9NSQ
     */
    @Value("${bblocks.map.baiduAk:'xncraBwKF8YGi1GoYKpFYxq4tvNw9NSQ'}")
    private  String _AK = "xncraBwKF8YGi1GoYKpFYxq4tvNw9NSQ";

    /**
     * 百度地图计算两经纬度之间的距离
     * @param longitude1 经度
     * @param latitude1 纬度
     * @param longitude2 经度
     * @param latitude2 纬度
     * @return
     */
    public  double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 维度
        double lat1 = (Math.PI / 180) * latitude1;
        double lat2 = (Math.PI / 180) * latitude2;

        // 经度
        double lon1 = (Math.PI / 180) * longitude1;
        double lon2 = (Math.PI / 180) * longitude2;

        // 地球半径
        double R = 6371;

        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

        return d;
    }

    /**
     * 百度地图获取两地导航位置（KM）
     */
    public  BigDecimal getNavDistance(double lng1, double lat1, double lng2, double lat2){
        BigDecimal navDistanceKm = null;
        //出发点经纬度
        String origin = lat1 + "," + lng1;
        //目的地经纬度
        String destination = lat2 + "," + lng2;
        //请求百度地图api
        String result = HttpUtil.get(_baseUrl + "origin=" + origin +
                "&" + "destination=" + destination + "&" + "ak=" + _AK);
        if(StrUtil.isNotBlank(result)){
			JSONObject jsonObject = JSONUtil.parseObj(result).getJSONObject("result") ;
			JSONArray jsonArray = jsonObject.getJSONArray("routes");
            JSONObject json = JSONUtil.parseObj(jsonArray.get(0).toString());
            //获取距离
            BigDecimal navDistance = new BigDecimal(json.getStr("distance"));
            navDistanceKm = navDistance.divide(new BigDecimal(1000))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
        }else
        	log.error("未计算出距离,异常结果：{}",result);
        return navDistanceKm;
    }

    public  Pair<Double, Double> adress2LonAndLat(String address){
        String url = null;
        try{
            url = "http://api.map.baidu.com/geocoding/v3/?address=" + URLEncoder.encode(address, DEFAULT_CHARSET.name()) + "&output=json&ak=" + _AK;
        }catch (UnsupportedEncodingException exception ){
            url = "http://api.map.baidu.com/geocoding/v3/?address=" + address + "&output=json&ak=" + _AK;
        }
        String json = HttpUtil.get(url);
        if(StrUtil.isNotBlank(json)){
            log.info("json:{}",json);
            JSONObject obj = JSONUtil.parseObj(json);
            if(obj.get("status").toString().equals("0")){
                double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
                double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");

                return Pair.of(lng,lat);
            }else{
                log.warn("地址：{} 未找到相匹配的经纬度!",address);
            }
        }else
            log.error("地址：{},异常结果：{}",address,json);
        return null;
    }


    public static void main(String[] args) throws Exception{
        MapUtil mapUtil = new MapUtil();
        String address = "北京市海淀区上地十街10号";
        Pair<Double, Double> result = mapUtil.adress2LonAndLat(address);
        System.out.println(result.getKey());
        System.out.println(result.getValue());

    }
}
